package zn.io.fastframe.modules.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.code.kaptcha.Producer;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import zn.io.fastframe.common.exception.RRException;
import zn.io.fastframe.modules.sys.dao.SysCaptchaDao;
import zn.io.fastframe.modules.sys.entity.SysCaptchaEntity;
import zn.io.fastframe.modules.sys.service.SysCaptchaService;

import java.awt.image.BufferedImage;
import java.util.Date;

@Service
public class SysCaptchaServiceImpl extends ServiceImpl<SysCaptchaDao, SysCaptchaEntity> implements SysCaptchaService {

    @Autowired
    private Producer producer;

    @Override
    public BufferedImage getCaptcha(String uuid) {
        if (StringUtils.isBlank(uuid)) {
            throw new RRException("uuid不能为空");
        }
        String code = producer.createText();

        SysCaptchaEntity sysCaptchaEntity = new SysCaptchaEntity();
        sysCaptchaEntity.setUuid(uuid);
        sysCaptchaEntity.setCode(code);

        sysCaptchaEntity.setExpireTime(DateUtils.addMinutes(new Date(), 5));

        baseMapper.insert(sysCaptchaEntity);

        return producer.createImage(code);
    }

    @Override
    public boolean validate(String uuid, String code) {
        SysCaptchaEntity sysCaptchaEntity = baseMapper.selectOne(new QueryWrapper<SysCaptchaEntity>().eq("uuid", uuid));
        if (sysCaptchaEntity == null) {
            return false;
        }

        baseMapper.deleteById(uuid);

        if (sysCaptchaEntity.getCode().equalsIgnoreCase(code)
                && sysCaptchaEntity.getExpireTime().getTime() >= System.currentTimeMillis()) {
            return true;
        }

        return false;
    }
}
